package ltd.hxya.novel.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PatternUtils {
    public static Matcher pattern(String pattern,String value){
        return Pattern.compile(pattern).matcher(value);
    }

    public static String simpleStrinMatching(Matcher matcher){
        String value = "";
        while (matcher.find()){
            value= matcher.group(1);
        }
        return value;
    }

    public static List<String> simpleCollectMatching(Matcher matcher){
        List<String> strings = new ArrayList<>();
        while (matcher.find()){
            String group = matcher.group(1);
            strings.add(group);
        }
        return strings;
    }

    public static String replaceLabel(String pattern,String text) {
      //  text = removeSpecial(text);
        //替换开始标签
        Matcher matcher = pattern(pattern, text);
        text = replace(matcher, text, "<p>","</p>");

        //替换结束标签
        text = removeSpace(text);
        return text;

    }

    private static String removeSpace(String text) {

        text = text.replaceAll("\\s", "");
        return text;
    }

    public static String replace(Matcher matcher,String text,String ... replaceStr){
        text="";
        while (matcher.find()){
           //System.out.println(matcher.group(1));
            for (int i = 1; i <=matcher.groupCount(); i++) {

                if (matcher.group(i)!=null){
                    String newStr= "<p>"+matcher.group(i)+"</p>";
                    text=text+newStr;
                }
            }
            //System.out.println(matcher.group(2));
           /* if (matcher.group(1)!=null){
                text = text.replace(matcher.group(1),replaceStr[0]);
            }*/


        }
        return text;
    }

    /**
     * 去除特殊字符
     * @param value
     * @return
     */
    public static String removeSpecial(String value){
        value = value.replaceAll("\\s", "");
        return value;
    }

    public static boolean checkPattern(String pattern, String value) {
        Matcher matcher = pattern(pattern, value);
        if (matcher.find()){
            return true;
        }
        return false;
    }

    public static String removePattern(String pattern,String value){
        String text = value.replaceAll(pattern, value);
        return text;
    }
}
